package com.hmdp.utils.interceptor;/**
 * ClassName:ReflashTokenIntercetor
 * Package:com.hmdp.utils.interceptor
 * Description:
 *
 * @Date:2022/3/26 11:36
 * @Author:lzp
 */

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ClassName:ReflashTokenIntercetor
 */
public class ReflashTokenIntercetor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    //构造函数
    public ReflashTokenIntercetor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // TODO 1.获取请求中请求头中的token
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            return true;
        }
        // TODO 2.基于token获取redis中的用户数据
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(SystemConstants.LOGIN_TOKEN_PRE + token);

        // TODO 3.判断用户是否存在
        if(userMap.isEmpty()){
            return true;
        }
        // TODO 4.将HashMap数据转换为UserDTO数据
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);

        // 5.存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);

        //TODO 6.动态更新token有效期
        stringRedisTemplate.expire(SystemConstants.LOGIN_TOKEN_PRE + token, SystemConstants.LOGIN_TOKEN_TTL, TimeUnit.MINUTES);

        // 7.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
